#coding:utf-8

import urllib
import urllib2
import json


def translate(str):
    URL = 'http://openapi.baidu.com/public/2.0/bmt/translate?from=%s&to=%s&q=%s&client_id=%s'
    API_Key = 'sypV6ThodHlHgUkNtMW5V2TL' #换成自己的APIKey
    url = URL % ('auto', 'auto', urllib.quote(str), API_Key)
    try:
        rsp = urllib2.urlopen(url)
    except Exception, e:
        raise Exception(u'链接服务器失败:' + str(e))
    rs = json.load(rsp)
    if 'error_code' in rs:
        raise Exception(u'翻译出错:' + rs['error_msg'])
    if rs['trans_result']:
        return rs['trans_result'][0]['dst']
    else:
        return u"无结果"
       #raise Exception('u无结果')